package com.xmg.p2p.business.service.impl;

import com.xmg.p2p.base.domain.Account;
import com.xmg.p2p.base.event.RechargeOfflineSuccessEvent;
import com.xmg.p2p.base.query.PageResult;
import com.xmg.p2p.base.service.IAccountService;
import com.xmg.p2p.base.util.UserContext;
import com.xmg.p2p.business.domain.RechargeOffline;
import com.xmg.p2p.business.mapper.RechargeOfflineMapper;
import com.xmg.p2p.business.query.RechargeOfflineQueryObject;
import com.xmg.p2p.business.service.IAccountFlowService;
import com.xmg.p2p.business.service.IRechargeOfflineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * lcd  2020/5/26
 * Description:
 */
@Service
public class RechargeOfflineServiceImpl implements IRechargeOfflineService {
    @Autowired
    private RechargeOfflineMapper rechargeOfflineMapper;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAccountFlowService accountFlowService;
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void save(RechargeOffline rechargeOffline) {
        rechargeOffline.setApplier(UserContext.getLogininfo());
        rechargeOffline.setApplyTime(new Date());
        rechargeOffline.setState(RechargeOffline.STATE_NORMAL);
        rechargeOfflineMapper.insert(rechargeOffline);
    }

    @Override
    public PageResult query(RechargeOfflineQueryObject qo) {
        int i = rechargeOfflineMapper.queryForCount(qo);
        if (i > 0) {
            List<RechargeOffline> query = rechargeOfflineMapper.query(qo);
            return new PageResult(query, i, qo.getCurrentPage(), qo.getPageSize());
        }
        return PageResult.empty(qo.getPageSize());
    }
    /**
     * 修改充值对象
     * 修改account
     * 修改状态
     **/
    @Override
    public void audit(long id, int state, String remark) {
        RechargeOffline r = rechargeOfflineMapper.selectByPrimaryKey(id);
        if (r != null && r.getState() == RechargeOffline.STATE_NORMAL) {
            r.setState(state);
            r.setRemark(remark);
            r.setAuditor(UserContext.getLogininfo());
            r.setAuditTime(new Date());
            if(state==RechargeOffline.STATE_AUDIT){
                Account applier = accountService.findById(r.getApplier().getId());
                applier.setUsableAmount(applier.getUsableAmount().add(r.getAmount()));
                accountFlowService.offLineCharge(r, applier);
                accountService.update(applier);
                applicationContext.publishEvent(new RechargeOfflineSuccessEvent(this, r));
            }
            rechargeOfflineMapper.updateByPrimaryKey(r);
        }
    }



}
